package pers.dean.gobang.boot.socket;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.springframework.stereotype.Service;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import com.alibaba.fastjson.JSONObject;

@Service
public class MyHandler implements WebSocketHandler {

	/**
	 *  在线用户列表
	 */
	private static final Map<String, WebSocketSession> users = new HashMap<>();
	
	
	@Override
	public void afterConnectionClosed(WebSocketSession arg0, CloseStatus arg1) throws Exception {
		// TODO Auto-generated method stub
		
	}

	/*
	 *  建立连接
	 */
	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		System.out.println("成功建立连接...");
		String clientId = session.getUri().toString().split("id=")[1];
		clientId = URLDecoder.decode(clientId, "UTF-8");
		System.out.println("clientId = "+clientId);
		if( clientId != null ) {
			users.put(clientId, session);
			session.sendMessage(new TextMessage("建立socket连接成功..."));
		}
		System.out.println("当前在线人数："+users.size());
	}

	/* 
	 * 服务器接收消息
	 */
	@Override
	public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
		JSONObject json = (JSONObject) JSONObject.parse((String) message.getPayload());
    	
		// 服务器收到消息后进行转发
		sendMessageToAll(json);

	}

	/**
	 * 发送消息给指定用户
	 * 
	 * @param clientId
	 * @param message
	 */
	public boolean sendMessageToUser(String clientId, TextMessage message) {
		try {
			clientId = URLDecoder.decode(clientId, "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		if( users.get(clientId) == null ) {
			return false;
		}
		WebSocketSession session = users.get(clientId);
		if( !session.isOpen() ) {
			return false;
		}
		try {
			session.sendMessage(message);
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	/**
	 * 发送消息给所有人（广播）
	 * 
	 * @param message
	 * @return
	 */
	public boolean sendMessageToAll(JSONObject jsonParam) {
		
		boolean result = true;
		Set<String> clientIds = users.keySet();
		WebSocketSession session = null;
		for(String clientId : clientIds) {
			try {
				session = users.get(clientId);
				if( session.isOpen() ) {
					JSONObject json = new JSONObject();
					json.put("id", jsonParam.getString("id"));
					json.put("message", jsonParam.getString("message"));
					json.put("type", jsonParam.getString("type")); // 0系统消息 1用户消息 2对战数据
					json.put("blackOrWhite", jsonParam.getString("blackOrWhite"));
					json.put("x", jsonParam.getString("x"));
					json.put("y", jsonParam.getString("y"));
					session.sendMessage(new TextMessage(json.toJSONString()));
				}
			} catch (Exception e) {
				e.printStackTrace();
				result = false;
			}
		}
		return result;
	}
	
	@Override
	public void handleTransportError(WebSocketSession session, Throwable e) throws Exception {
		if( session.isOpen() ) {
			session.close();
		}
		users.remove(getClientId(session));
		System.out.println("连接出现异常："+e);
		
	}

	@Override
	public boolean supportsPartialMessages() {
		return false;
	}
	
	/**
     * 获取用户标识
     * @param session
     * @return
     */
    private Integer getClientId(WebSocketSession session) {
        try {
            Integer clientId = (Integer) session.getAttributes().get("WEBSOCKET_USERID");
            return clientId;
        } catch (Exception e) {
            return null;
        }
    }

}
